import {
  SubscribeMessage,
  MessageBody,
  ConnectedSocket,
  OnGatewayConnection,
  OnGatewayDisconnect,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';

@WebSocketGateway({
  path: '/socket.io',
  cors: {
    origin: (_req, callback) => {
      callback(null, true);
    },
    credentials: true,
  },
})
export class WsGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  handleConnection(client: Socket) {
    // Handle connection event
    client.emit('opend', new Date() + '此客户端已成功打开！');
    this.server.emit('joined', new Date() + '有一个新客户成功加入！');
  }

  handleDisconnect(client: Socket) {
    // Handle disconnection event
    console.info('已退出');
  }

  @SubscribeMessage('sendMsg')
  handleMessage(
    @MessageBody() data: string,
    @ConnectedSocket() client: Socket,
  ) {
    // Handle received message
    console.info('获取客户端 add 事件发送的数据', data);
    this.server.emit('add', data); // Broadcast the message to all connected clients
  }
}
